package com.first.common.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.util.UUID;

/**
 * @program: first-project
 * @description:
 * @author: 闫锦超
 * @create: 2023-05-30 09:45
 **/

@Component
public class OssUtil {
    public static String uploadFile(MultipartFile file){
        //获取原始文件名
        String filename = file.getOriginalFilename();
        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = "oss-cn-shanghai.aliyuncs.com";


        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = "LTAI5tGTzc8qdAASVqGiogQF";
        String accessKeySecret = "5rf87tqYb8lYFGqhtDiYl0cF5lALVP";
        // 填写Bucket名称，例如examplebucket。
        String bucketName = "zys-oss";
        // 填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。
        String objectName = UUID.randomUUID()+filename;
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        String src = "https://" + bucketName + "." + endpoint + "/" + objectName;

        try {
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, new ByteArrayInputStream(file.getBytes()));
            ossClient.putObject(putObjectRequest);
        } catch (OSSException var17) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + var17.getErrorMessage());
            System.out.println("Error Code:" + var17.getErrorCode());
            System.out.println("Request ID:" + var17.getRequestId());
            System.out.println("Host ID:" + var17.getHostId());
        } catch (Exception var18) {
            System.out.println("Caught an ClientException, which means the client encountered a serious internal problem while trying to communicate with OSS, such as not being able to access the network.");
            System.out.println("Error Message:" + var18.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }

        }
        return src;
    }

}